package com.pubinfo.passbook.common.service.master.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.annotation.RequiredLog;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.entity.TSystemRole;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.model.bo.witeoff.UserPassbookListParam;
import com.pubinfo.passbook.common.model.dto.financial.PassbookPageParamObj;
import com.pubinfo.passbook.common.model.dto.financial.PassbookParamAcct;
import com.pubinfo.passbook.common.model.ruler.PassbookInformation;
import com.pubinfo.passbook.common.model.vo.PassbookVo;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.common.service.master.TRabbitmqPersonService;
import com.pubinfo.passbook.common.utils.XmlTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import static com.pubinfo.passbook.common.model.constant.RoleEnum.*;

/**
 *
 */
@Service
@Slf4j
public class TPassbookServiceImpl extends ServiceImpl<TSourcePassbookMapper, TPassbook> implements TPassbookService {

    @Value("${file.uploadFolder}")
    private String filePath;
    @Autowired
    TRabbitmqPersonService personService;
    @RequiredLog("票据列表查询")
    @Override
    public MyPage<PassbookVo> listTPassbook(PassbookPageParamObj paramObj, TSystemRole role, String acctId) {
        String acctStr = paramObj.getAcct();
        String acct = null;
        if (StringUtils.isNotBlank(acctStr) && acctStr.indexOf("@") > 0) {
            acct = acctStr.substring(0, acctStr.indexOf("@"));
            paramObj.setAcct(acct);
        }
        MyPage<PassbookVo> iPage = paramObj.getMyPage();
        if (role == null || USER.getRoleCode().equals(role.getRoleCode())) {
            paramObj.setAcctId(acctId);
        } else {
            if (AUDITOR.getRoleCode().equals(role.getRoleCode())) {
                paramObj.setDistrictId(role.getDistrictId());
                paramObj.setNsrsbh(role.getNsrsbh());
            } else if (Department.getRoleCode().equals(role.getRoleCode())) {
                paramObj.setAcctId(acctId);
            }
        }
        paramObj.setRoleCode(role.getRoleCode());
        iPage = baseMapper.listTPassbookByParam(iPage, paramObj);
        return iPage;
    }
    @Override
    public IPage<PassbookVo> findAutoReimbursementByStaffCode(UserPassbookListParam listParam, TSystemRole role, String nsrsbh) {
        final IPage<TPassbook> iPage = this.page(listParam.getPage("create_time"));
        // listParam.setAcct("330226197511120040");
        final String acctStr = listParam.getAcct();
        String acct = acctStr;
        if (acctStr.indexOf("@") > 0) {
            acct = acctStr.substring(0, acctStr.indexOf("@"));
        }
        String idNo = null;
        if (role == null || USER.getRoleCode().equals(role.getRoleCode())) {
            idNo = this.personService.findIdNoByAcct(acct);
            listParam.setPayerPartyCode(idNo);
        } else {
            listParam.setNsrsbh(nsrsbh);
        }
        return baseMapper.findAutoReimbursementByStaffCode(iPage, listParam);
    }
    
    @Override
    public List<TPassbook> getPassbookById(final List<String> invoiceId) {
        if (!CollectionUtils.isEmpty(invoiceId)) {
            return baseMapper.selectPassbookByInvoiceList(invoiceId);
        }
        return null;
    }
    
    @Override
    public Boolean updateInvoice() {
        List<TPassbook> passbookList = list();
        List<TPassbook> newPassbookList = new ArrayList<>();
        passbookList.stream().forEach(passbook -> {
            Boolean isExit = false;
            if (passbook.getInvoiceStatus() == null) {
                
                passbook.setInvoiceStatus(0);
                isExit = true;
            }
            String xmlStr = passbook.getEinvoiceXml();
            if (StringUtils.isNotBlank(xmlStr)) {
                if (XmlTool.isXmlDocument(xmlStr)) {
                    
                    Document document = null;
                    try {
                        document = DocumentHelper.parseText(xmlStr);
                    } catch (DocumentException e) {
                        log.error("解析票据数据失败", e);
                    }
                    Element element = document.getRootElement().element("EInvoiceData");
                    if (element != null) {
                        Element main = element.element("Main");
                        Element mainExt = main.element("MainExt");
                        if (mainExt != null) {
                            Element relatedInvoiceCode = mainExt.element("RelatedInvoiceCode");
                            Element relatedInvoiceNumber = mainExt.element("RelatedInvoiceNumber");
                            
                            passbook.setInvoiceStatus(1);
                            if (relatedInvoiceCode != null && StringUtils.isNotBlank(relatedInvoiceCode.getText())) {
                                passbook.setInvoiceStatus(0);
                                passbook.setRelatedInvoiceCode(relatedInvoiceCode.getText().replaceAll("\"", ""));
                                isExit = true;
                                
                            }
                            if (relatedInvoiceNumber != null && StringUtils.isNotBlank(relatedInvoiceNumber.getText())) {
                                passbook.setInvoiceStatus(0);
                                passbook.setRelatedInvoiceNumber(relatedInvoiceNumber.getText().replaceAll("\"", ""));
                                
                                isExit = true;
                            }
                            
                        }
                        
                    }
                }
            }
            if (isExit) {
                
                newPassbookList.add(passbook);
            }
        });
        return saveOrUpdateBatch(newPassbookList);
    }
    
    @Override
    public IPage<TPassbook> selectTPassbookByAcct(PassbookParamAcct acct) {
        final IPage<TPassbook> iPage = this.page(acct.getPage("create_time"));
        return baseMapper.selectPassbookByAcct(iPage, acct.getAcct());
    }

    @Override
    public IPage<PassbookInformation> selectTPassbookInformationByAcct(PassbookParamAcct acct) {
        final IPage<PassbookInformation> iPage = this.page(acct.getPage("create_time"));
        return baseMapper.selectTPassbookInformationByAcct(iPage, acct.getAcct());
    }

    @Override
    public List<TPassbook> selectPassbookByFpdmAndFphm(List<TPassbook> passbook) {
        return baseMapper.selectPassbookByFpdmAndFphm(passbook);
    }

}




